const { warn, error, info, success, getPrint } = require("../utils/log_tool");
const {
    formatTimeInMillisec,
    formatDate,
    convert,
} = require("../utils/transform_tool");
const { BaseCommand } = require("./base");
const { formatData } = require("./share_data");

class IntervalCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        let commandCfgs = data.commands;
        // 特殊处理字符的情况
        if (typeof commandCfgs === "string") {
            commandCfgs = formatData(commandCfgs);
        }
        const _now = Date.now();
        let asyncId;
        const delay = convert(data.delay, "millisecond");
        const repeat = data.repeat || 0;
        let times = 0;
        if (data.run_immediately) {
            warn(`立即执行一次任务`);
            await this.exec(commandCfgs, this.depth + 1);
        }
        // 正在执行任务。（执行中，不能再次发起）
        let isRunningTask = 0;
        const timer = setInterval(async () => {
            if (isRunningTask && !data.concurrent) return;
            info("");
            times += 1;
            if (repeat) {
                if (times >= repeat) {
                    clearInterval(timer);
                }
            }
            if (data.repeat_mapping) {
                this.shareData[data.repeat_mapping] = repeat;
            }
            if (data.times_mapping) {
                this.shareData[data.times_mapping] = times;
            }
            warn(
                `开始执行间隔任务[${asyncId}] (${times}/${repeat || "∞"})`,
                undefined,
                undefined,
                true,
            );
            isRunningTask++;
            await this.exec(commandCfgs, this.depth + 1);
            isRunningTask--;
        }, delay);
        asyncId =
            timer[
                Object.getOwnPropertySymbols(timer).find(
                    (v) => v.description === "asyncId",
                )
            ];
        info("");
        warn(
            `将每间隔 ${formatTimeInMillisec(delay, true)} 执行定时任务[${asyncId}] (${times}/${repeat || "∞"})`,
            undefined,
            undefined,
            true,
        );
    }

    getRequiredParams() {
        return ["commands", "delay"];
    }
}

module.exports = {
    IntervalCommand,
};
